package com.cola;

import java.io.*;
import java.util.Properties;

/**
 * @Grup:com.hxh
 * @Auther:cola
 * @Data:2021/3/9-2021-03-12:41
 * @version:1.0
 *
 * Properties:
 * properties可以用来做配置文件
 * Javaweb javaeeg开发中通常会用到
 *
 * ResourceBundle 只读
 * properties 可读可写
 */
public class PropertiesDemo {
    public static String version="";
    public static  String username="";
    public static String password="";
    /*
    *
    * 静态代码块,只执行一次
    * 对属性文件的写入操作
    *
    * */
    static {
        //readConfig();
    }
    private static void writeConfig(String version,String username,String password){
        Properties p=new Properties();
        p.put("app.version",version);
        p.put("db.username",username);
        p.put("db.password",password);
        OutputStream out= null;
        try {
            out = new FileOutputStream("FIileAndIO/src/main/resources/config.properties");
            //写文件
            p.store(out,"update config");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    /*
    *读取properties配置文件
    * */
    private static void readConfig(){
        Properties p=new Properties();
        InputStream inStream=null;
        try {

            //通过当前线程的类加载器对象,来加载指定包下的配置文件
            //InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("FIileAndIO/src/main/resources/config.properties");
            inStream =new FileInputStream("FIileAndIO/src/main/resources/config.properties");
            p.load(inStream);//加载文件
            //properties中获取数据
            version=p.getProperty("app.version");
            username=p.getProperty("db.username");
            password=p.getProperty("db.password");
            inStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        writeConfig("10","cola","123456");
        readConfig();
        System.out.println(PropertiesDemo.version);
        System.out.println(PropertiesDemo.username);
        System.out.println(PropertiesDemo.password);
    }
}
